const mysql = require('mysql')

const defaultConfig = {
    host: '139.199.195.236',
    user: 'film',
    password: 'JWjcprmrbbZTDYC7',
    database: 'film',
    connectionLimit: 20
}

const AsyncMysqljs = function(config = defaultConfig){
    const pool = mysql.createPool(config)
    const q = function (sql, values) {
        return new Promise((resolve, reject) => {
            pool.getConnection((err, conn) => {
                if (err) return reject(err)
                conn.query(sql, values, (err, rows) => {
                    if (err) {
                        console.log(err);
                        reject({
                            msg: err,
                            err: 1
                        })
                    }
                    else{
                        resolve(rows)
                    }
                    conn.release()
                })
            })
        })
    }
    
    /*
    从数据库中查询一条数据，返回值是对象，而非数组
    最好在sql语句中加一个唯一的限制条件
    */
    const get = (sql, values) => {
        try {
            return q(sql, values).then(rows => {
                if (rows.length >= 1) {
                    return rows[0]
                }
            })
        } catch (err) {
            return new Promise((resolve, reject) => {
                reject(err)
            })
        }
    }

    return {query: q, delete: q, update: q, insert: q, execute: q, get}
}

module.exports = AsyncMysqljs